package com.lyc.lojbackendcommon.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * 声明队列和死信队列
 */
@Configuration
@Slf4j
public class RabbitmqConfig {
    
    // 正常队列
    public static final String QUEUE_CODE= "queue_code";
    // 正常交换机
    public static final String EXCHANGE_CODE ="exchange_code";
    // 正常路由
    public static final String ROUTINGKEY_CODE ="routing.code";

    // 死信队列
    public static final String QUEUE_CODE_DLX = "queue_code_dlx";
    // 死信交换机
    public static final String EXCHANGE_CODE_DLX = "exchange_code_dlx";
    // 死信路由
    public static final String ROUTINGKEY_DLX_CODE ="routing.dlx.code";


    //声明交换机
    @Bean(EXCHANGE_CODE)
    public Exchange EXCHANGE_CODE(){
        return new DirectExchange(EXCHANGE_CODE,true,false);
    }

    //声明死信交换机
    @Bean(EXCHANGE_CODE_DLX)
    public Exchange EXCHANGE_CODE_DLX_EXCHANGE(){
        return new DirectExchange(EXCHANGE_CODE_DLX,true,false);
    }

    //声明正常队列
    @Bean(QUEUE_CODE)
    public Queue QUEUE_CODE(){
        Map<String, Object> args = new HashMap<>(2);
        //正常队列中的消息被废弃后会被路由到死信队列(前提是有绑定死信队列)
        // 绑定死信交换机
        args.put("x-dead-letter-exchange", EXCHANGE_CODE_DLX);
        // 绑定路由key
        args.put("x-dead-letter-routing-key", ROUTINGKEY_DLX_CODE);
        return new Queue(QUEUE_CODE,true,false,false, args);
    }
    
    //声明死信队列
    @Bean(QUEUE_CODE_DLX)
    public Queue QUEUE_CODE_DLX_QUEUE(){
        return new Queue(QUEUE_CODE_DLX,true,false,false);
    }

    
    //正常交换机绑定正常队列
    @Bean
    public Binding BINDING_QUEUE_CODE(){
        return new Binding(QUEUE_CODE,
                Binding.DestinationType.QUEUE, EXCHANGE_CODE,
                ROUTINGKEY_CODE,null);
    }

    //死信交换机绑定死信队列
    @Bean
    public Binding BINDING_DLX_QUEUE_CODE(){
        return new Binding(QUEUE_CODE_DLX,
                Binding.DestinationType.QUEUE, EXCHANGE_CODE_DLX,
                ROUTINGKEY_DLX_CODE,null);
    }
}
